import type {ApiParams, OptionField, SelectorInfo} from "./type.ts";
import {ref} from "vue";
import api from "@/utils/api";
import {message} from "ant-design-vue";

// 创建独立的多选服务实例
export const createSelector3Service = (config: {
    apiPath: string;
    apiParams: ApiParams;
    modalName: string;
    optionField: OptionField;
}) => {
    const fetching = ref(false);
    const selectorInfo = ref<SelectorInfo>({
        index: -1,
        desc: undefined,
        option: [],
    });
    const selectedValues = ref<string[]>([]);
    const newNames = ref<string[]>([]);
    const newInput = ref<any>(undefined);

    const reset = () => {
        selectorInfo.value = {
            index: -1,
            desc: undefined,
            option: [],
        };
        selectedValues.value = [];
        newNames.value = [];
    };

    // 获取列表
    const fetch = async (searchValue: string, masterValue?: string) => {
        try {
            fetching.value = true;
            const searchRef = ref<any>(searchValue);
            if (config.apiParams.searchKey === 'NA') {
                searchRef.value = undefined;
            }
            const masterRef = ref<any>(masterValue);
            if (config.apiParams.masterKey === 'NA') {
                masterRef.value = undefined;
            }
            const response = await api.get(config.apiPath, {
                params: {
                    [config.apiParams.searchKey]: searchRef.value,
                    [config.apiParams.masterKey]: masterRef.value,
                }
            });
            selectorInfo.value.option = response.data;

            if (searchValue && searchValue.length > 0) {
                // 在多选模式下，我们可能需要处理多个新名称
                // 这里简单地将搜索值添加到新名称列表中
                if (!newNames.value.includes(searchValue)) {
                    newNames.value.push(searchValue);
                }
            }
        } catch (error) {
            message.error(`获取${config.modalName}列表失败`);
            console.error(`获取${config.modalName}列表失败:`, error);
        } finally {
            fetching.value = false;
        }
    };

    // 搜索方法
    const onSearch = async (searchValue: string, masterValue?: string) => {
        await fetch(searchValue, masterValue);
        if(searchValue.length>0){
            newInput.value=searchValue;
        }
    };

    const onFocus = async (masterValue?: string) => {
        await fetch('', masterValue);
    };

    // 选择变化 - 多选版本
    const onChange = (values: string[]) => {
        selectedValues.value = [...new Set(values)];

        // 检查是否有新创建的项目
        newNames.value = values.filter(value =>
            !selectorInfo.value.option.some(option =>
                option[config.optionField.value] === value
            )
        );
        newInput.value=undefined;
    };

    const onBlur = () => {
        if(newInput.value){
            selectedValues.value.push(newInput.value);
            onChange(selectedValues.value);
        }
    };

    return {
        fetching,
        selectorInfo,
        selectedValues,
        reset,
        onSearch,
        onFocus,
        onBlur,
        onChange,
    };
};